package tool

import (
	"encoding/json"
	"math/rand"
	"reflect"
	"strings"
)

func RandStr(length int) string {
	var str strings.Builder
	bytes := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
	for i := 0; i < length; i++ {
		str.WriteString(string([]byte(bytes)[rand.Intn(len(bytes))]))
	}
	return str.String()
}

func StructToMap(data interface{}) map[string]any {
	dataType := reflect.TypeOf(data)
	if dataType.Kind() != reflect.Struct {
		panic("不支持的转换类型")
	}
	var paramsMap map[string]any
	jsonByte, err := json.Marshal(data)
	if err != nil {
		panic(err)
	}
	err = json.Unmarshal(jsonByte, &paramsMap)
	if err != nil {
		panic(err)
	}
	return paramsMap
}
